package com.example.paimengshop.client_socket;

import org.json.simple.JSONObject;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Objects;


public class SendToServer
{
    private Socket socket;
    private ObjectOutputStream oos;

    public void setClientSocket(Socket socket)
    {
        this.socket = socket;
    }

    public Socket getClientSocket()
    {
        return socket;
    }



    public SendToServer()
    {

    }

    public SendToServer(Socket socket)
    {
        this.socket = socket;
        try
        {
            oos = new ObjectOutputStream(socket.getOutputStream());
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public JSONObject WriteMessageByJson(String messageKey, String messageContent)
    {
        if(Objects.equals(messageKey, ""))
        {
            System.out.println("Key不能为空！");
            return null;
        }
        else
        {
            JSONObject jsonObject =  new JSONObject();
            jsonObject.put(messageKey, messageContent);
            return jsonObject;
        }
    }

    public void Send(JSONObject jsonObject)
    {
        if(oos != null)
        {
            try
            {
                oos.writeObject(jsonObject);
                oos.flush();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        else
        {
            System.out.println("输出流为空！");
        }
    }
}
